/**
 * 遍历目录
 */

const fs = require('fs');
const path = require('path');

function eachFolder(filePath, extensions) {
  let stats = fs.lstatSync(filePath);
  let info = {
      path: filePath,
      name: path.basename(filePath)
    };

  if (stats.isDirectory()) {
    info.type = "folder";

    let files = [];

    fs.readdirSync(filePath).map(function(child) {
      return eachFolder(filePath + '/' + child, extensions);
    }).forEach(function(file, i) {
      if (
        file &&
        (file.type === 'file' || (file.type === 'folder' && file.children))
      ) {
        files.push(file);
      }
    });

    if (files.length) {
      info.children = files;
    }
  } else {
    if (extensions.length && extensions.indexOf(path.extname(filePath).slice(1)) < 0) {
      return false;
    } else {
      info.type = "file";
    }
  }

  return info;
}

/**
 * @param folderPath 目录路径
 * @param extensions 文件扩展名列表。若为空，遍历所有文件；
 */
export default function dirTree(folderPath, extensions = []) {
  let tree = eachFolder(folderPath, extensions);
  return tree;
}